package PowerWord.Core.Plan;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import PowerWord.Core.Data.Defines;
import PowerWord.Core.Data.WordList;
import PowerWord.Core.Data.WordList.SearchFlag;

public class Free extends Duty {

	public Free(WordList l) {
		super(l);
	}

	@Override
	protected void CreateWork(String fromWord, String toWord, int flag) {
		int left = fromWord.equals("") ? 0 : 
			list.Search(fromWord, SearchFlag.Larger);
		int right = toWord.equals("") ? list.GetCount() - 1 :
			list.Search(toWord, SearchFlag.Less);
		subList = list.GetSubList(left, right, flag);
	}
	
	public void SaveSubList() {
		try {
			DataOutputStream saveData = new DataOutputStream(
											new FileOutputStream(Defines.SaveDirectory + "FreeList"));
			saveData.writeInt(subList.length);
			for(int i : subList){
				saveData.writeInt(i);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	protected void LoadSubList() {
		try {
			DataInputStream saveData = new DataInputStream(
											new BufferedInputStream(
													new FileInputStream(Defines.SaveDirectory + "FreeList")));
			int size = saveData.readInt();
			subList = new Integer[size];
			for(int i=0; i<size; ++i) {
				subList[i] = saveData.readInt();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void GotoSubListMode(WordList list, String fromWord, String toWord, byte flag, boolean random) {
		int left = fromWord.equals("") ? 0 : 
			list.Search(fromWord, SearchFlag.Larger);
		int right = toWord.equals("") ? list.GetCount() - 1 :
			list.Search(toWord, SearchFlag.Less);
		subList = list.GetSubList(left, right, flag);
		if(random){
			Random();
		}
	}
}
